package com.example.demoserver.controller;

import com.example.demoserver.entity.InteAppalarm;
import com.example.demoserver.entity.InteApplog;
import com.example.demoserver.entity.InteAppstate;
import com.example.demoserver.entity.InteGateway;
import com.example.demoserver.mqtt.TestMqttHandler;
import com.example.demoserver.mqtt.TestServer;
import com.example.demoserver.service.InteAppalarmService;
import com.example.demoserver.service.InteGatewayService;
import com.example.demoserver.service.impl.InteAppstateServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/app")
@RequiredArgsConstructor
@Component
public class InteAppStateController {
    private final InteAppstateServiceImpl inteAppstateService;
    private final InteGatewayService inteGatewayService;
    private final InteAppalarmService inteAppalarmService;
    @PostMapping("/updatestate")
    public boolean updateState (@RequestBody InteAppstate inteAppstate) {
        boolean bol=inteAppstateService.updateById(inteAppstate);
        return bol;
    }
    @GetMapping("/selectstate")
    public List<InteAppstate> selectState () {
        List<InteAppstate> list=inteAppstateService.selectAll();
        return list;
    }

    @GetMapping("/setfault")
    public boolean setFault (Integer type,Integer state) throws InterruptedException {
        List<String> list=new ArrayList<>();
        list.add("设备管理");
        list.add("生产管理");
        list.add("运营管理");
        InteAppstate inteAppstate=new InteAppstate();
        inteAppstate.setId(type);
        inteAppstate.setAppfault(state);
        if(state==1){
            if(type!=1){
                inteAppstate.setAppstate(1);
            }
            InteAppalarm inteAppalarm=new InteAppalarm();
            inteAppalarm.setAlarmtype(1);
            inteAppalarm.setAlarminfo(list.get(type-1)+"应用发生无法处理异常，请管理员处理。");
            inteAppalarm.setAlarmtime(Util.getNowTime());
            inteAppalarmService.save(inteAppalarm);
        }
        boolean bol1=inteAppstateService.updateById(inteAppstate);
        return bol1;
    }

    @PostConstruct
    public void initState() {
        List<InteAppstate> list=inteAppstateService.selectAll();
        for (InteAppstate i: list) {
            i.setAppstate(1);
            i.setAppfault(0);
            inteAppstateService.updateById(i);
        }
        List<InteGateway> list1=inteGatewayService.selectAll();
        for (InteGateway i: list1) {
            i.setGatewaystate(1);
            inteGatewayService.updateById(i);
        }

    }
    @GetMapping("/healthy")
    public boolean isHealthy () {
        return true;
    }
}
